package andev.aandroidlib.util;

import android.opengl.GLES20;
import android.util.Log;

/**
 * Created by lzy1g on 2015/9/29.
 */
public class AOpenGLES2 {
    private static String TAG = "AOpenGLES2";

    public static int compileShader(int type, String shaderCode) {
        final int shaderID = GLES20.glCreateShader(type);
        if (shaderID == 0) {
            Log.v(TAG, "Create Shader Failed" + "\n" + GLES20.glGetError());
            return 0;
        }

        GLES20.glShaderSource(shaderID, shaderCode);
        GLES20.glCompileShader(shaderID);

        final int[] compileResult = new int[1];
        GLES20.glGetShaderiv(shaderID, GLES20.GL_COMPILE_STATUS, compileResult, 0);
//Log.v(TAG, "Results of compiling source:" + "\n" + shaderCode + "\n" + GLES20.glGetShaderInfoLog(shaderID));

        if (compileResult[0] == 0) {
            Log.v(TAG, "Compile Shader Failed");
            GLES20.glDeleteShader(shaderID);
            return 0;
        }
        Log.v(TAG, "Compile Shader Success");
        return shaderID;
    }

    public static int linkProgram(int vertexShaderID, int fragmentShaderID) {
        final int programID = GLES20.glCreateProgram();
        if (programID == 0) {
            Log.v(TAG, "Create Program Failed" + "\n" + GLES20.glGetError());
            return 0;
        }

        GLES20.glAttachShader(programID, vertexShaderID);
        GLES20.glAttachShader(programID, fragmentShaderID);

        GLES20.glLinkProgram(programID);

        final int[] linkResult = new int[1];
        GLES20.glGetProgramiv(programID, GLES20.GL_LINK_STATUS, linkResult, 0);
//Log.v(TAG, "Results of linking program:\n" + GLES20.glGetProgramInfoLog(programID)+GLES20.glGetError());
        if (linkResult[0] == 0) {
            Log.v(TAG, "Link Program Failed");
            GLES20.glDeleteProgram(programID);
            return 0;
        }
        Log.v(TAG, "Link Program Success");
        return programID;
    }

    public static boolean validateProgram(int programID) {
        GLES20.glValidateProgram(programID);

        final int[] validateResult = new int[1];
        GLES20.glGetProgramiv(programID, GLES20.GL_VALIDATE_STATUS, validateResult, 0);
        Log.v(TAG, "Results of validating program: " + validateResult[0] + "\n" + GLES20.glGetProgramInfoLog(programID) + GLES20.glGetError());
        return validateResult[0] != 0;
    }
}
